package com.sig;

import com.sig.bean.User;
import com.sig.service.AuthorityService;
import com.sig.service.RedisService;
import com.sig.service.UserService;
import net.sf.ehcache.CacheManager;
import org.nutz.dao.Dao;
import org.nutz.dao.util.Daos;
import org.nutz.integration.quartz.NutQuartzCronJobFactory;
import org.nutz.ioc.Ioc;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
import org.nutz.plugins.cache.dao.CachedNutDaoExecutor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class MainSetup implements Setup {
    private static final Log log = Logs.get();

    public void init(NutConfig conf) {
        Ioc ioc = conf.getIoc();
        Dao dao = ioc.get(Dao.class);
        Daos.createTablesInPackage(dao, "com.sig", false);
        Daos.migration(dao, User.class, true, false);

        // 初始化默认根用户
        if (dao.count(User.class) == 0) {
            UserService us = ioc.get(UserService.class);
            us.add("admin", "123456");
        }
        // 获取NutQuartzCronJobFactory从而触发计划任务的初始化与启动
        ioc.get(NutQuartzCronJobFactory.class);

        // 测试发送邮件
        // try {
        // HtmlEmail email = ioc.get(HtmlEmail.class);
        // email.setSubject("测试NutzBook");
        // email.setMsg("This is a test mail ... :-)" +
        // System.currentTimeMillis());
        // email.addTo("810715859@qq.com");// 请务必改成您自己的邮箱啊!!!
        // email.buildMimeMessage();
        // email.sendMimeMessage();
        // } catch (Exception e) {
        // e.printStackTrace();
        // }

        AuthorityService as = ioc.get(AuthorityService.class);
        as.initFormPackage("com.sig");
//        as.checkBasicRoles(admin);

        CacheManager cacheManager = ioc.get(CacheManager.class);
        log.debug("Ehcache CacheManager = " + cacheManager);

        CachedNutDaoExecutor.DEBUG = true;

//        JedisPool jedisPool = ioc.get(JedisPool.class);
//
//        try (Jedis jedis = jedisPool.getResource()) { // Java7的语法
//            String re = jedis.set("_nutzbook_test_key", "http://www.sig.com");
//            log.debug("redis say : " + re);
//            re = jedis.get("_nutzbook_test_key");
//            log.debug("redis say : " + re);
//        } finally {
//        }
//
//        RedisService redis = ioc.get(RedisService.class);
//        redis.set("hi", "sig");
//        log.debug("redis say again : " + redis.get("hi"));


        log.debug("Tomcat服务启动完毕...");
    }

    public void destroy(NutConfig conf) {
    }
}
